import { debounce } from "@/utils";
import { tryOnMounted, tryOnUnmounted, useDebounceFn, useResizeObserver } from "@vueuse/core";
import { ref } from "vue";

export interface WindowResizeOptions {
  once?: boolean;
  immediate?: boolean;
  listenerOptions?: AddEventListenerOptions | boolean;
}

export function useResize(fn: (width: number, height: number) => void, container: string, wait = 150) {
  const w = ref(0);
  const h = ref(0);

  const handler = (width: number, height: number) => {
    fn(width, height);
  };
  const handleSize = debounce(handler, wait);

  tryOnMounted(() => {
    const c = document.getElementById(container);
    const { stop } = useResizeObserver(c, (entries) => {
      const entry = entries[0];
      const { width, height } = entry.contentRect;
      (w.value = width), (h.value = height);
      handleSize.exec(width, height);
    });

    tryOnUnmounted(() => {
      stop();
    });
  });

  return { width: w, height: h };
}

export function useMainResize(fn: (width: number, height: number) => void, wait = 150) {
  return useResize(fn, "main", wait);
}

export function useWindowResize(fn: () => void, wait = 150, options?: WindowResizeOptions) {
  let handler = () => {
    fn();
  };
  const handleSize = useDebounceFn(handler, wait);
  handler = handleSize;

  const start = () => {
    if (options && options.immediate) {
      handler();
    }
    window.addEventListener("resize", handler);
  };

  const stop = () => {
    window.removeEventListener("resize", handler);
  };

  tryOnMounted(() => {
    start();
  });

  tryOnUnmounted(() => {
    stop();
  });
  return { start, stop };
}
